package com.example.printlib;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class PrintMainActivity extends AppCompatActivity {
    private static final String TAG = "PrintMainActivity";
    private Button printButton;
    private FrameLayout backButton;
    private TextView tvState;
    private ImageView imageView;
    private PrintEngine engine = PrintEngine.getInstance();

    private ArrayList<String> uriArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_main);
        backButton = findViewById(R.id.btn_back);
        printButton = findViewById(R.id.btn_print);
        tvState = findViewById(R.id.tv_state);
        imageView = findViewById(R.id.iv_print);
        backButton.setOnClickListener(v -> finish());
        printButton.setOnClickListener(v -> {
                    Log.i(TAG, "printButton: " + uriArrayList.size());
                    if (uriArrayList.isEmpty()) {
                        Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (String path : uriArrayList) {
                        engine.addPrintQueue(path);
                    }
                    uriArrayList.clear();

                }
        );
        imageView.setOnClickListener(v -> pickResource("image/*", 101));
        engine.initEngine(this, () -> {
            Log.i(TAG, "onCreate: ");
            engine.addPrintCallback(printCallback);
        });
    }

    private PrintService.PrintCallback printCallback = new PrintService.PrintCallback() {
        @Override
        public void onPrintState(PrintService.PrintServerStatus state, String description) {
            Log.i(TAG, "state: " + state + " description: " + description);
            tvState.setText(description);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        engine.removePrintCallback(printCallback);
        engine.unit(this);
    }


    private void pickResource(String type, int code) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // 限定选择图片文件
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); // 允许选择多个文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 授予读取URI的权限
        startActivityForResult(intent, code);
        Log.i(TAG, "pickResource: ");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || (data == null)) {
            return;
        }
        uriArrayList.clear();
        // 注意：当allowMultiple为true时，data.getData()将返回null，实际数据在ClipData中
        ClipData clipData = data.getClipData();
        if (clipData != null) {
            for (int i = 0; i < clipData.getItemCount(); i++) {
                Uri uri = clipData.getItemAt(i).getUri();
                Log.i(TAG, "onActivityResult: " + uri);
                uriArrayList.add(uri.toString());
                // 可以在此处添加代码以处理每个URI，例如显示图片或获取其路径
            }
            imageView.setImageURI(Uri.parse(uriArrayList.get(0)));
        } else {
            // 仅在未启用allowMultiple或设备/应用不支持时才会执行此代码块
            Uri uri = data.getData();
            uriArrayList.add(uri.toString());
            imageView.setImageURI(uri);
            Log.i(TAG, "onActivityResult: single uri" + uri);
        }
    }
}